﻿#region 文件信息

// FileName: SoCafeShop/Sohobloo.SoAuth.Web/RoleUserController.cs
// Author: Sohobloo
// CreateTime: 2013/07/02 20:12
// UpdateTime: 2013/07/05 0:51

#endregion

#region 引用

using System;
using System.ComponentModel.Composition;
using System.Linq;
using System.Web.Mvc;
using Sohobloo.SoAuth.Service;
using Sohobloo.SoAuth.Web.Models;

#endregion

namespace Sohobloo.SoAuth.Web.Controllers
{
    [Export]
    public class RoleUserController : Controller
    {
        [Import]
        public IRoleService RoleService { get; set; }

        public ActionResult Index(Guid? id)
        {
            var isRoleSpecified = id.HasValue;

            var roleUsersModel = new RoleUsersModel
            {
                RoleId = id
            };
            var roleList = RoleService.GetRoleList();
            roleUsersModel.RoleList = roleList.Select(
                r => new RoleModel
                {
                    Id = r.Id,
                    RoleName = r.RoleName
                });

            //var roleList = RoleService.GetRoleList().Select(
            //    f => new SelectListItem
            //    {
            //        Text = f.RoleName,
            //        Value = f.Id.ToString(),
            //        Selected = f.Id == id
            //    });
            //ViewBag.RoleList = roleList;

            if(isRoleSpecified)
            {
                var roleUserList = RoleService.GetRole(id.Value).RoleUsers;

                roleUsersModel.RoleUserList = roleUserList.Select(
                    u => new UserModel
                    {
                        Id = u.Id,
                        UserName = u.UserName,
                        NickName = u.NickName,
                        Email = u.Email,
                        UserStatus = u.UserStatus
                    });
            }

            return View(roleUsersModel);
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Add(RoleUsersModel roleUsersModel)
        {
            RoleService.AddUser(roleUsersModel.RoleId.Value, roleUsersModel.UserName);
            return RedirectToAction(
                "Index",
                new
                {
                    id = roleUsersModel.RoleId
                });
        }

        public ActionResult Remove(Guid? id, Guid userId)
        {
            RoleService.RemoveUser(id.Value, userId);

            return RedirectToAction(
                "Index",
                new
                {
                    id
                });
        }
    }
}